package org.healer.simple_juc;

public class TestPC {
    public static void main(String[] args) {
        SynContainer syn = new SynContainer();
        Productor p = new Productor(syn);
        Consumer c1 = new Consumer(syn);
        Consumer c2 = new Consumer(syn);
        Consumer c3 = new Consumer(syn);
        p.start();
        c1.start();
        c2.start();
        c3.start();
    }
}
class Productor extends Thread{
    SynContainer container;
    public Productor(SynContainer container){
        this.container = container;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            container.push(new Chicken(i));
            System.out.println("生产了第"+i+"只鸡");
        }
    }

}
class Consumer extends Thread{
    SynContainer container;
    public Consumer(SynContainer container){
        this.container = container;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Chicken chicken = container.pop();
            System.out.println("消费了第"+chicken.getId()+"只鸡");

        }
    }
}
// 产品
class Chicken{
    private int id;
    public Chicken(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }
}
class SynContainer {
    // 需要一个容器大小
    Chicken[] chickens = new Chicken[10];
    int length;
    //生产者放入产品
    public synchronized void push(Chicken chicken){
        //如果容器满了就等待消费者
        if(length==chickens.length){
            try {
                //通知消费者
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        chickens[length]=chicken;
        length++;
        //通知消费着
        this.notifyAll();
    }

    //消费者消费产品
    public synchronized Chicken pop(){
        //判断是否能消费
        if(length==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        length--;
        Chicken chicken = chickens[length];
        //通知生产者
       this.notifyAll();

        return chicken;
    }
}